package com.kvin.wechatpay;

import android.app.Activity;

import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Kvin on 2017/5/23.
 * step-1>register WX Open Developing account and open paying function
 * step-2>register app to wx
 * step-3>request paying info
 * step-4>launch paying
 */
public class WXUtils {
    private Activity act;
    private IWXAPI wxApi;

    private WXUtils(Activity act, String appId) {
        this.act = act;
        this.wxApi = WXAPIFactory.createWXAPI(act, appId);
        this.wxApi.registerApp(appId);//register to wx
    }

    public WXUtils getInstance(Activity act, String appId) {
        return new WXUtils(act, appId);
    }

    /**
     * wechat pay
     */
    public boolean wechatPay(PayReq req) {
        return wxApi.sendReq(req);
    }

    /**
     * wechat pay
     */
    public boolean wechatPay(JSONObject response) {
        PayReq req = new PayReq();
        //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
        try {
            req.appId = response.getString(Cons.APP_ID);
            req.partnerId = response.getString(Cons.PARTNER_ID);
            req.prepayId = response.getString(Cons.PREPAY_ID);
            req.nonceStr = response.getString(Cons.NONCESTR);
            req.timeStamp = response.getString(Cons.TIME_STAMP);
            req.packageValue = response.getString(Cons.PACKAGE);
            req.sign = response.getString(Cons.SIGN);
            req.extData = "app data"; // optional
            return wxApi.sendReq(req);
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * whether is supported
     */
    public static boolean isPaySupported(IWXAPI iwxapi) {
        if (iwxapi == null) {
            throw new RuntimeException("iwxapi is null");
        }
        return iwxapi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
    }

    /**
     * register to wx
     */
    @Deprecated
    public void registerApp(String appId) {
        wxApi.registerApp(appId);
    }


}
